﻿using System;
using CrawlerFramework.ConfigEntity;
using CrawlerFramework.CrawlerEngine;
using CrawlerFramework.Models;
namespace CrawlerFramework.PageProcessor
{
    public class BasePageProcessorBuilder : IPageProcessorBuilder
    {
        private static BasePageProcessorBuilder _instance;

        /// <summary>
        /// The singleton of PageProcessor builder
        /// </summary>
        public static BasePageProcessorBuilder Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new BasePageProcessorBuilder();

                return _instance;
            }
        }

        /// <summary>
        /// Get the concrete implementation of PageProcessor class based on the linkConfig.Guid using Reflection method.
        /// </summary>
        /// <param name="linkConfig"></param>
        /// <param name="link"></param>
        /// <param name="doneEvent"></param>
        /// <returns></returns>
        public virtual PageProcessor GetPageProcessor(ICrawlerEngine crawlerEngine, LinkConfig linkConfig, Link link, ILogService logger,System.Threading.EventWaitHandle doneEvent)
        {
            var pageProcessorClass = linkConfig.GetReflectorTypeString();
            if (string.IsNullOrEmpty(pageProcessorClass))
                throw new ArgumentException("The PageProcessor class name is empty, check the link config file to fix this issue");

            var type = Type.GetType(pageProcessorClass);
            if (type == null)
                return null;

            var instance = Activator.CreateInstance(type, linkConfig, link);
            if (instance is PageProcessor)
            {
                var pageProcessor = (PageProcessor)instance;
                pageProcessor.CrawlerEngine = crawlerEngine;
                pageProcessor.DoneEvent = doneEvent;
                pageProcessor.Logger = logger;

                return pageProcessor;
            }

            return null;
        }
    }
}